package com.holic.spring.custom.fetcher;

import com.holic.spring.custom.GraphQLMappingDefinition;
import com.holic.spring.custom.resolver.MethodArgumentResolver;
import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;

import java.lang.reflect.Method;

/**
 * @ClassName DynamicMethodDataFetcher
 * @Description
 * @Author Neil
 * @Date 2024/11/12 17:13
 * @Version V1.0
 **/
public class DynamicMethodDataFetcher implements DataFetcher<Object> {

    private GraphQLMappingDefinition definition;

    public DynamicMethodDataFetcher(GraphQLMappingDefinition definition){
        this.definition = definition;
    }

    @Override
    public Object get(DataFetchingEnvironment environment) throws Exception {
        Method method = definition.getMethod();
        Object bean = definition.getBean();
        Object[] arguments = MethodArgumentResolver.getInstance().resolve(environment, method);
        try {
            return method.invoke(bean, arguments);
        }catch(Exception ex){
            throw (Exception)ex.getCause();
        }
    }

}
